package com.aly.beanValidate.core.validator.impl;

import com.aly.beanValidate.core.FieldDefinition;
import com.aly.beanValidate.core.GlobalConfigs;
import com.aly.beanValidate.core.validator.CheckValidator;
import com.aly.beanValidate.core.validator.Name;
import com.aly.beanValidate.i.BeanInfo;
import com.aly.beanValidate.i.FileInfo;
import com.aly.beanValidate.i.FileInfos;
import org.dom4j.Element;

import java.util.regex.Pattern;

@Name("Pattern")
public class PatternValidate extends CheckValidator {
    private final Pattern pattern;
    private final String regex;

    public PatternValidate(Element element, GlobalConfigs globalConfigs) {
        super(element, globalConfigs);
        regex = element.attributeValue("regex");
        pattern = Pattern.compile(regex);
    }

    @Override
    public StringBuffer doValidate(FieldDefinition field, Object val, BeanInfo bean, FileInfo fileInfo, FileInfos fileInfos) {
        if (!pattern.matcher(String.valueOf(val)).matches()) {
            return new StringBuffer("不满足 正则:[").append(regex).append("]");
        }
        return null;
    }
}
